<template>
  <div class="app-container">
    <!-- 数据统计卡片区域 -->
    <el-row :gutter="20" class="data-cards">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="data-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon size="40" color="#409EFF">
                <Document />
              </el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">今日支付订单</div>
              <div class="card-value">{{ todayStats.paidOrders }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="data-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon size="40" color="#409EFF">
                <Money />
              </el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">今日实际收入</div>
              <div class="card-value">¥ {{ todayStats.actualIncome }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="data-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon size="40" color="#409EFF">
                <User />
              </el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">未到账订单(总)</div>
              <div class="card-value">{{ todayStats.unpaidOrders }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="data-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon size="40" color="#409EFF">
                <ShoppingBag />
              </el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">已售后订单(总)</div>
              <div class="card-value">{{ todayStats.purchasedItems }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 待处理事项区域 - 独占第二行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span class="card-header-title">待处理事项</span>
          </template>
          <div class="pending-items">
            <div class="pending-item">
              <span class="item-name">待支付订单</span>
              <span class="item-count" :class="{ 'highlight': pendingStats.pendingPayment > 0 }">{{ pendingStats.pendingPayment }}</span>
            </div>
            <div class="pending-item">
              <span class="item-name">待配送订单</span>
              <span class="item-count" :class="{ 'highlight': pendingStats.pendingDelivery > 0 }">{{ pendingStats.pendingDelivery }}</span>
            </div>
            <div class="pending-item">
              <span class="item-name">已完成订单</span>
              <span class="item-count">{{ pendingStats.completedOrders }}</span>
            </div>
            <div class="pending-item">
              <span class="item-name">售后处理中</span>
              <span class="item-count" :class="{ 'highlight': pendingStats.afterSalesProcessing > 0 }">{{ pendingStats.afterSalesProcessing }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品总览和指数总览区域 - 占第三行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 商品总览 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="12">
        <el-card class="stats-card">
          <template #header>
            <span class="card-header-title">商品总览</span>
          </template>
          <el-row :gutter="20" class="stats-row">
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ productStats.offlineProducts }}</div>
              <div class="stat-label">已下架</div>
              <div class="stat-desc">商品数量</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ productStats.onlineProducts }}</div>
              <div class="stat-label">已上架</div>
              <div class="stat-desc">商品数量</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ productStats.outOfStock }}</div>
              <div class="stat-label">库存售罄</div>
              <div class="stat-desc">商品数量</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ productStats.totalProducts }}</div>
              <div class="stat-label">商品总数</div>
              <div class="stat-desc">全部商品</div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 指数总览 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="12">
        <el-card class="stats-card">
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
            <span class="card-header-title">指数总览</span>
              <el-button 
                @click="fetchIndexStats" 
                size="small" 
                type="primary" 
                :icon="RefreshRight"
                circle
                title="刷新指数数据"
              />
            </div>
          </template>
          <el-row :gutter="20" class="stats-row">
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ indexStats.todayTotal }}</div>
              <div class="stat-label">今日订单</div>
              <div class="stat-desc">今天创建订单</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ indexStats.pendingTotal }}</div>
              <div class="stat-label">待处理</div>
              <div class="stat-desc">待支付+待配送</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ indexStats.monthTotal }}</div>
              <div class="stat-label">本月订单</div>
              <div class="stat-desc">本月已支付订单</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ indexStats.completionRate }}</div>
              <div class="stat-label">完成率</div>
              <div class="stat-desc">订单完成占比</div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单统计和图表区域 - 占第四行 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 订单统计 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="12">
        <el-card>
          <template #header>
            <span class="card-header-title">订单统计</span>
          </template>
          <div class="order-stats">
            <div class="order-stat-item">
              <div class="stat-title">本月订单总数</div>
              <div class="stat-main-value">{{ orderStats.monthTotal }}</div>
              <div class="stat-compare" :class="orderStats.monthCompare.type">
                {{ orderStats.monthCompare.text }}
              </div>
            </div>
            <div class="order-stat-item">
              <div class="stat-title">本周订单总数</div>
              <div class="stat-main-value">{{ orderStats.weekTotal }}</div>
              <div class="stat-compare" :class="orderStats.weekCompare.type">
                {{ orderStats.weekCompare.text }}
              </div>
            </div>
            <div class="order-stat-item">
              <div class="stat-title">本月销售额</div>
              <div class="stat-main-value">¥{{ orderStats.monthSales }}</div>
              <div class="stat-compare" :class="orderStats.monthSalesCompare.type">
                {{ orderStats.monthSalesCompare.text }}
              </div>
            </div>
            <div class="order-stat-item">
              <div class="stat-title">本周销售额</div>
              <div class="stat-main-value">¥{{ orderStats.weekSales }}</div>
              <div class="stat-compare" :class="orderStats.weekSalesCompare.type">
                {{ orderStats.weekSalesCompare.text }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 图表区域 -->
      <el-col :xs="24" :sm="12" :md="12" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <div class="chart-title-wrapper">
                <span class="card-header-title">趋势图表</span>
                <el-select
                    v-model="chartDataType"
                    @change="handleDataTypeChange"
                    size="small"
                    style="margin-left: 10px; width: 100px;"
                >
                  <el-option label="订单数" value="orders" />
                  <el-option label="销售额" value="sales" />
                  <el-option label="客户数" value="customers" />
                </el-select>
              </div>
              <div class="date-picker-wrapper">
                <el-date-picker
                    v-model="chartDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="handleDateRangeChange"
                    size="small"
                />
              </div>
            </div>
          </template>
          <div ref="chartContainer" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index">
import { reactive, ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { Document, Money, User, ShoppingBag, RefreshRight } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { 
  getTodayPaidOrderCount, 
  getTodayBusinessIncome,
  getUnpaidToMerchantOrderCount,
  getAfterSalesOrderCount,
  getPendingPaymentOrderCount,
  getPendingDeliveryOrderCount,
  getCompletedOrderCount,
  getAfterSalesProcessingOrderCount,
  // 新增指数统计API
  getTodayAllOrderCount,
  getPendingOrderCount,
  getMonthOrderCount,
  getAllOrderCount,
  // 新增每日订单量API
  getDailyOrdersChart,
  // 新增订单统计API
  getOrderStats
} from '@/api/order/orders';

// 从goods.js导入商品统计API
import {
  getOnlineGoodsCount,
  getOfflineGoodsCount,
  getTotalGoodsCount,
  getOutOfStockGoodsCount
} from '@/api/order/goods';

import useUserStore from '@/store/modules/user'

const user = useUserStore()

// 打印完整状态
console.log('user state:', user.$state)

// 打印关键字段
console.log('token:', user.token)
console.log('roles:', user.roles)
console.log('permissions:', user.permissions)




// 今日统计数据
const todayStats = reactive({
  paidOrders: 0,           // 今日支付订单数量
  actualIncome: 0,         // 今日实际收入
  unpaidOrders: 0,         // 未到账订单总数（替换原来的visitors）
  purchasedItems: 0        // 已售后订单总数
})

// 待处理事项统计 - 改为reactive格式
const pendingStats = reactive({
  pendingPayment: 0,        // 待支付订单 (Pending Payment Orders)
  pendingDelivery: 0,       // 待配送订单 (Pending Delivery Orders)  
  completedOrders: 0,       // 已完成订单 (Completed Orders)
  afterSalesProcessing: 0   // 售后处理中 (After Sales Processing)
})

// 商品统计
const productStats = reactive({
  offlineProducts: 5,    // 已下架商品数量 
  onlineProducts: 34,    // 已上架商品数量 
  outOfStock: 1,         // 库存售罄商品数量 
  totalProducts: 40      // 商品总数 
})

// 指数统计 - 改为更实用的数据
const indexStats = reactive({
  todayTotal: 0,        // 今日订单总数
  pendingTotal: 0,      // 待处理订单总数  
  monthTotal: 0,        // 本月订单总数
  completionRate: '0%'  // 订单完成率
})

// 订单统计原始数据
const orderStatsData = reactive({
  // 当前数据
  monthTotal: 10,
  weekTotal: 5,
  monthSales: 5,
  weekSales: 3,

  // 上期数据（用于计算同比）
  previousMonthTotal: 8,
  previousWeekTotal: 6,
  previousMonthSales: 4,
  previousWeekSales: 2
})

// 计算同比数据的函数
const calculateCompare = (current, previous, period = '上期') => {
  if (previous === 0) {
    return { text: '新增数据', type: 'increase' }
  }

  const changeRate = ((current - previous) / previous * 100).toFixed(1)
  const isIncrease = changeRate > 0
  const isEqual = changeRate == 0

  if (isEqual) {
    return { text: `同比${period} 持平`, type: 'no-data' }
  }

  return {
    text: `同比${period} ${isIncrease ? '+' : ''}${changeRate}%`,
    type: isIncrease ? 'increase' : 'decrease'
  }
}

// 订单统计计算属性
const orderStats = computed(() => ({
  monthTotal: orderStatsData.monthTotal,
  weekTotal: orderStatsData.weekTotal,
  monthSales: orderStatsData.monthSales,
  weekSales: orderStatsData.weekSales,
  monthCompare: calculateCompare(orderStatsData.monthTotal, orderStatsData.previousMonthTotal, '上月'),
  weekCompare: calculateCompare(orderStatsData.weekTotal, orderStatsData.previousWeekTotal, '上周'),
  monthSalesCompare: calculateCompare(orderStatsData.monthSales, orderStatsData.previousMonthSales, '上月'),
  weekSalesCompare: calculateCompare(orderStatsData.weekSales, orderStatsData.previousWeekSales, '上周')
}))

// 图表相关 - 确保初始日期范围有效
const chartContainer = ref(null)
const chartDateRange = ref([])  // 先设置为空数组
const chartDataType = ref('orders')
let chartInstance = null

// 初始化日期范围（页面加载时设置默认值）
const initializeDateRange = () => {
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(endDate.getDate() - 7);  // 默认显示最近7天
  
  chartDateRange.value = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ];
  
  console.log('初始化日期范围:', chartDateRange.value);
}

// fetchChartData 函数
const fetchChartData = async (startDate, endDate, dataType = 'orders') => {
  // 参数验证
  if (!startDate || !endDate) {
    console.error(' 日期参数缺失:', { startDate, endDate });
    throw new Error('开始日期和结束日期不能为空');
  }
  
  // 如果是查询订单数据，调用后端接口
  if (dataType === 'orders') {
    try {
      const shopId = user.shopId || 1;
      
      // 确保日期格式正确
      let formattedStartDate = startDate;
      let formattedEndDate = endDate;
      
      if (startDate instanceof Date) {
        formattedStartDate = startDate.toISOString().split('T')[0];
      }
      if (endDate instanceof Date) {
        formattedEndDate = endDate.toISOString().split('T')[0];
      }

      console.log('原始开始日期:', startDate);
      console.log('原始结束日期:', endDate);
      console.log('格式化开始日期:', formattedStartDate);
      console.log('格式化结束日期:', formattedEndDate);

      const response = await getDailyOrdersChart(shopId, formattedStartDate, formattedEndDate);
      
      console.log('每日订单API返回:', response);

      if (response.code === 200) {
        const { title, unit, data } = response.data;
        
        // 生成完整的日期范围
        const dates = generateDateRange(formattedStartDate, formattedEndDate);
        const values = [];
        
        // 创建数据映射
        const dataMap = {};
        data.forEach(item => {
          const dateKey = item.date_value;
          dataMap[dateKey] = item.orders_count || 0;
        });
        
        // 填充所有日期的数据，没有数据的日期显示为0
        dates.forEach(date => {
          values.push(dataMap[date] || 0);
        });


        return {
          dates,
          values,
          title,
          unit
        };
      } else {
        throw new Error(response.msg || '获取每日订单数据失败');
      }
    } catch (error) {
      console.error('获取每日订单数据失败，使用假数据:', error);
      // fallback到假数据
    }
  }

  // 其他数据类型或出错时使用假数据
  const dates = generateDateRange(startDate, endDate);
  let values = [];
  let title = '';
  let unit = '';

  switch (dataType) {
    case 'orders':
      title = '每日订单数量';
      unit = '单';
      values = dates.map((date) => {
        const dayOfWeek = new Date(date).getDay();
        const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
        const baseOrders = isWeekend ? 15 : 8;
        const randomFactor = 0.3 + Math.random() * 0.7;
        return Math.floor(baseOrders * randomFactor);
      });
      break;

    case 'sales':
      title = '每日销售额';
      unit = '元';
      values = dates.map((date) => {
        const dayOfWeek = new Date(date).getDay();
        const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
        const baseSales = isWeekend ? 1500 : 800;
        const randomFactor = 0.5 + Math.random() * 0.8;
        return Math.floor(baseSales * randomFactor);
      });
      break;

    case 'customers':
      title = '每日客户数';
      unit = '人';
      values = dates.map((date) => {
        const dayOfWeek = new Date(date).getDay();
        const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
        const baseCustomers = isWeekend ? 25 : 12;
        const randomFactor = 0.4 + Math.random() * 0.9;
        return Math.floor(baseCustomers * randomFactor);
      });
      break;
  }

  return {
    dates,
    values,
    title,
    unit
  };
}

// 生成日期范围
const generateDateRange = (start, end) => {
  const dates = []
  const current = new Date(start)
  const endDate = new Date(end)

  while (current <= endDate) {
    dates.push(current.toISOString().split('T')[0])
    current.setDate(current.getDate() + 1)
  }
  return dates
}

// ====== 四个模块的API调用函数 ======

// 获取今日统计数据
const fetchTodayStats = async () => {
  try {
    const shopId = user.shopId || 1;
    
    // 并行调用四个API获取统计数据
    const [orderCountResponse, incomeResponse, unpaidResponse, afterSalesResponse] = await Promise.all([
      getTodayPaidOrderCount(shopId),
      getTodayBusinessIncome(shopId),
      getUnpaidToMerchantOrderCount(shopId),
      getAfterSalesOrderCount(shopId)
    ]);
    
    // 将查询到的值分别赋给对应的字段
    todayStats.paidOrders = orderCountResponse.data;
    todayStats.actualIncome = incomeResponse.data;
    todayStats.unpaidOrders = unpaidResponse.data;      // 未到账订单总数
    todayStats.purchasedItems = afterSalesResponse.data; // 已售后订单总数
    
    console.log('今日支付订单数量:', orderCountResponse.data);
    console.log('今日商家实际收入:', incomeResponse.data);
    console.log('未到账订单总数:', unpaidResponse.data);
    console.log('已售后订单总数:', afterSalesResponse.data);
    
  } catch (error) {
    console.error('获取今日统计数据失败:', error);
    // 发生错误时可以设置默认值
    todayStats.paidOrders = 0;
    todayStats.actualIncome = 0;
    todayStats.unpaidOrders = 0;
    todayStats.purchasedItems = 0;
  }
}

// 获取待处理事项统计
const fetchPendingStats = async () => {
  try {
    const shopId = user.shopId || 1;
    
    // 并行调用四个API获取待处理事项统计
    const [pendingPaymentResponse, pendingDeliveryResponse, completedResponse, afterSalesProcessingResponse] = await Promise.all([
      getPendingPaymentOrderCount(shopId),
      getPendingDeliveryOrderCount(shopId),
      getCompletedOrderCount(shopId),
      getAfterSalesProcessingOrderCount(shopId)
    ]);
    
    // 将查询到的值分别赋给对应的字段
    pendingStats.pendingPayment = pendingPaymentResponse.data;
    pendingStats.pendingDelivery = pendingDeliveryResponse.data;
    pendingStats.completedOrders = completedResponse.data;
    pendingStats.afterSalesProcessing = afterSalesProcessingResponse.data;

    console.log('待支付订单:', pendingStats.pendingPayment);
    console.log('待配送订单:', pendingStats.pendingDelivery);
    console.log('已完成订单:', pendingStats.completedOrders);
    console.log('售后处理中:', pendingStats.afterSalesProcessing);
    
  } catch (error) {
    console.error('获取待处理事项统计失败:', error);
    // 发生错误时设置默认值
    pendingStats.pendingPayment = 0;
    pendingStats.pendingDelivery = 0;
    pendingStats.completedOrders = 0;
    pendingStats.afterSalesProcessing = 0;
  }
}

// 获取商品统计数据
const fetchProductStats = async () => {
  try {
    const shopId = user.shopId || 1;

    console.log('当前店铺ID:', shopId);
    
    // 并行调用四个API获取商品统计数据
    const [offlineResponse, onlineResponse, outOfStockResponse, totalResponse] = await Promise.all([
      getOfflineGoodsCount(shopId),    // 已下架商品数量
      getOnlineGoodsCount(shopId),     // 已上架商品数量
      getOutOfStockGoodsCount(shopId), // 库存售罄商品数量
      getTotalGoodsCount(shopId)       // 商品总数
    ]);
    
    // 将查询到的值分别赋给对应的字段
    productStats.offlineProducts = offlineResponse.data;    // 已下架商品数量
    productStats.onlineProducts = onlineResponse.data;      // 已上架商品数量
    productStats.outOfStock = outOfStockResponse.data;      // 库存售罄商品数量
    productStats.totalProducts = totalResponse.data;       // 商品总数
    
    // 输出赋值结果
    console.log('商品统计数据赋值结果:');
    console.log('已下架商品:', productStats.offlineProducts);
    console.log('已上架商品:', productStats.onlineProducts);
    console.log('库存售罄商品:', productStats.outOfStock);
    console.log('商品总数:', productStats.totalProducts);
    
  } catch (error) {
    console.error('获取商品统计数据失败:', error);
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      response: error.response
    });
    
    // 发生错误时设置默认值
    productStats.offlineProducts = 0;
    productStats.onlineProducts = 0;
    productStats.outOfStock = 0;
    productStats.totalProducts = 0;
    
    console.log('设置默认值后的商品数据:', {
      offlineProducts: productStats.offlineProducts,
      onlineProducts: productStats.onlineProducts,
      outOfStock: productStats.outOfStock,
      totalProducts: productStats.totalProducts
    });
  }
}

// 获取指数统计数据
const fetchIndexStats = async () => {
  try {
    const shopId = user.shopId || 1;
    
    console.log('=== 开始获取指数统计数据 ===');
    console.log('当前店铺ID:', shopId);
    
    // 并行调用API获取指数统计数据
    const [todayAllResponse, pendingResponse, monthResponse, allOrderResponse, completedResponse] = await Promise.all([
      getTodayAllOrderCount(shopId),      // 今日订单总数
      getPendingOrderCount(shopId),       // 待处理订单总数
      getMonthOrderCount(shopId),         // 本月订单总数
      getAllOrderCount(shopId),           // 订单总数（用于计算完成率）
      getCompletedOrderCount(shopId)      // 已完成订单数量
    ]);
    

    // 赋值基础数据
    indexStats.todayTotal = todayAllResponse.data;
    indexStats.pendingTotal = pendingResponse.data;
    indexStats.monthTotal = monthResponse.data;
    
    // 计算订单完成率
    const allOrders = allOrderResponse.data;
    const completedOrders = completedResponse.data;

    console.log('订单统计详情:');
    console.log('- 总订单数（已支付）:', allOrders);
    console.log('- 已完成订单数:', completedOrders);

    if (allOrders > 0) {
      // 确保已完成订单数不会超过总订单数
      const validCompletedOrders = Math.min(completedOrders, allOrders);
      const rate = Math.round((validCompletedOrders / allOrders) * 100);
      indexStats.completionRate = rate + '%';
      
      if (completedOrders > allOrders) {
        console.warn(' 数据异常：已完成订单数超过总订单数');
        console.warn(`已完成: ${completedOrders}, 总数: ${allOrders}`);
      }
    } else {
      indexStats.completionRate = '0%';
    }
    
    // 输出最终赋值结果
    console.log('今日订单总数:', indexStats.todayTotal);
    console.log('待处理订单总数:', indexStats.pendingTotal);
    console.log('本月订单总数:', indexStats.monthTotal);
    console.log('订单完成率:', indexStats.completionRate, `(${completedOrders}/${allOrders})`);
    console.log('=== 指数统计数据获取完成 ===');
    
  } catch (error) {
    console.error(' 获取指数统计数据失败:', error);
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      response: error.response
    });
    
    // 设置默认值
    indexStats.todayTotal = 0;
    indexStats.pendingTotal = 0;
    indexStats.monthTotal = 0;
    indexStats.completionRate = '0%';
    
    console.log('设置默认值后的指数数据:', {
      todayTotal: indexStats.todayTotal,
      pendingTotal: indexStats.pendingTotal,
      monthTotal: indexStats.monthTotal,
      completionRate: indexStats.completionRate
    });
  }
}

// 获取订单统计数据
const fetchOrderStats = async () => {
  try {
    const shopId = user.shopId || 1;
    
    console.log('=== 开始获取订单统计数据 ===');
    console.log('店铺ID:', shopId);
    
    const response = await getOrderStats(shopId);
    
    console.log('订单统计API返回:', response);
    
    if (response.code === 200) {
      const data = response.data;
      
      // 更新订单统计数据
      orderStatsData.monthTotal = data.monthTotal || 0;
      orderStatsData.weekTotal = data.weekTotal || 0;
      orderStatsData.monthSales = data.monthSales || 0;
      orderStatsData.weekSales = data.weekSales || 0;
      orderStatsData.previousMonthTotal = data.previousMonthTotal || 0;
      orderStatsData.previousWeekTotal = data.previousWeekTotal || 0;
      orderStatsData.previousMonthSales = data.previousMonthSales || 0;
      orderStatsData.previousWeekSales = data.previousWeekSales || 0;
      
      console.log(' 订单统计数据更新结果:');
      console.log('本月订单:', orderStatsData.monthTotal);
      console.log('本周订单:', orderStatsData.weekTotal);
      console.log('本月销售额:', orderStatsData.monthSales);
      console.log('本周销售额:', orderStatsData.weekSales);
      console.log('上月订单:', orderStatsData.previousMonthTotal);
      console.log('上周订单:', orderStatsData.previousWeekTotal);
      console.log('上月销售额:', orderStatsData.previousMonthSales);
      console.log('上周销售额:', orderStatsData.previousWeekSales);
      console.log('=== 订单统计数据获取完成 ===');
      
    } else {
      throw new Error(response.msg || '获取订单统计数据失败');
    }
  } catch (error) {
    console.error(' 获取订单统计数据失败:', error);
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      response: error.response
    });
    
    // 设置默认值
    orderStatsData.monthTotal = 0;
    orderStatsData.weekTotal = 0;
    orderStatsData.monthSales = 0;
    orderStatsData.weekSales = 0;
    orderStatsData.previousMonthTotal = 0;
    orderStatsData.previousWeekTotal = 0;
    orderStatsData.previousMonthSales = 0;
    orderStatsData.previousWeekSales = 0;
    
    console.log('设置默认值后的订单统计数据:', orderStatsData);
  }
}

// 修正初始化图表函数
const initChart = async () => {
  if (!chartContainer.value) return

  // 确保日期范围有效
  if (!chartDateRange.value || chartDateRange.value.length !== 2) {
    console.warn(' 日期范围无效，使用默认值');
    initializeDateRange();
  }

  let startDate = chartDateRange.value[0];
  let endDate = chartDateRange.value[1];
  
  // 确保日期不为空
  if (!startDate || !endDate) {
    console.error(' 日期为空，初始化默认日期');
    initializeDateRange();
    startDate = chartDateRange.value[0];
    endDate = chartDateRange.value[1];
  }
  
  console.log('初始化图表，日期范围:', startDate, '到', endDate);

  try {
    const chartData = await fetchChartData(startDate, endDate, chartDataType.value);

  if (chartInstance) {
      chartInstance.dispose();
  }

    chartInstance = echarts.init(chartContainer.value);

    // 保持原有的图表配置...
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.8)',
      textStyle: {
        color: '#fff'
      },
      formatter: function(params) {
        const date = params[0].axisValue.replace('\n', ' ')
        const value = params[0].value
        return `${date}<br/>${chartData.title}: ${value}${chartData.unit}`
      }
    },
    grid: {
      left: '50px',
      right: '20px',
      top: '20px',
      bottom: '50px'
    },
    xAxis: {
      type: 'category',
      data: chartData.dates.map(date => {
        const d = new Date(date)
        return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}\n${d.getFullYear()}`
      }),
      axisLabel: {
        fontSize: 10,
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: {
        fontSize: 10,
        color: '#666',
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: '#e0e0e0'
        }
      }
    },
    series: [{
      data: chartData.values,
      type: 'line',
      smooth: true,
      lineStyle: {
        color: '#409EFF',
        width: 2
      },
      itemStyle: {
        color: '#409EFF'
      },
      symbol: 'circle',
      symbolSize: 4
    }]
  }

  chartInstance.setOption(option)
  } catch (error) {
    console.error(' 初始化图表失败:', error);
  }
}

// 修正日期范围改变处理
const handleDateRangeChange = () => {
  console.log(' 日期范围改变:', chartDateRange.value);
  
  if (chartDateRange.value && chartDateRange.value.length === 2) {
    const startDate = chartDateRange.value[0];
    const endDate = chartDateRange.value[1];
    
    if (startDate && endDate) {
      console.log(' 日期有效，重新初始化图表:', startDate, '到', endDate);
      initChart();
    } else {
      console.warn('日期无效:', { startDate, endDate });
    }
  } else {
    console.warn('日期范围格式错误:', chartDateRange.value);
  }
}

// 数据类型改变处理
const handleDataTypeChange = () => {
  initChart()
}

// 初始化数据
const initData = () => {
  fetchTodayStats()
  fetchPendingStats()
  fetchProductStats()
  fetchIndexStats()
  fetchOrderStats()
}

// 页面加载时初始化数据和图表
onMounted(async () => {
  await nextTick()
  
  // 初始化日期范围
  initializeDateRange();
  
  // 初始化图表
    initChart()
  
  // 获取所有统计数据
  await Promise.all([
    fetchTodayStats(),
    fetchPendingStats(),
    fetchProductStats(),
    fetchIndexStats(),
    fetchOrderStats()
  ])
})

// 页面卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})

// 刷新所有统计数据
const refreshAllStats = async () => {
  console.log(' 开始刷新所有统计数据...');
  
  try {
    await Promise.all([
      fetchTodayStats(),
      fetchPendingStats(),
      fetchProductStats(),
      fetchIndexStats(),
      fetchOrderStats()
    ]);
    console.log(' 所有统计数据刷新完成');
    // 可以添加成功提示
    // ElMessage.success('数据刷新成功');
  } catch (error) {
    console.error(' 数据刷新失败:', error);
    // 可以添加错误提示
    // ElMessage.error('数据刷新失败');
  }
}

// 可以在浏览器控制台手动调用
window.refreshAllStats = refreshAllStats;
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.data-cards {
  margin-bottom: 20px;
}

.data-card {
  margin-bottom: 20px;

  .card-content {
    display: flex;
    align-items: center;
    padding: 10px;

    .card-icon {
      margin-right: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      background: rgba(64, 158, 255, 0.1);
      border-radius: 8px;
    }

    .card-info {
      flex: 1;

      .card-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }

      .card-value {
        font-size: 24px;
        font-weight: bold;
        color: #333;
      }
    }
  }
}

.card-header-title {
  font-weight: bold;
  color: #333;
}

.pending-items {
  .pending-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .item-name {
      font-size: 14px;
      color: #666;
    }

    .item-count {
      font-size: 16px;
      font-weight: bold;
      color: #333;

      &.highlight {
        color: #f56c6c;
      }
    }
  }
}

.stats-card {
  height: 100%;

  .stats-row {
    .stat-item {
      text-align: center;
      padding: 10px 0;

      .stat-value {
        font-size: 20px;
        font-weight: bold;
        color: #409EFF;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 12px;
        color: #666;
        margin-bottom: 4px;
      }

      .stat-desc {
        font-size: 10px;
        color: #999;
        line-height: 1.2;
      }
    }
  }
}

// 订单统计样式
.order-stats {
  .order-stat-item {
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .stat-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
    }

    .stat-main-value {
      font-size: 24px;
      font-weight: bold;
      color: #333;
      margin-bottom: 6px;
    }

    .stat-compare {
      font-size: 12px;
      font-weight: 500;

      &.no-data {
        color: #999;

        &::before {
          content: '→ ';
          font-size: 10px;
        }
      }

      &.increase {
        color: #67c23a;

        &::before {
          content: '↗ ';
          font-size: 10px;
        }
      }

      &.decrease {
        color: #f56c6c;

        &::before {
          content: '↘ ';
          font-size: 10px;
        }
      }
    }
  }
}

// 图表样式
.chart-card {
  height: 100%;

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .chart-title-wrapper {
      display: flex;
      align-items: center;
    }

    .date-picker-wrapper {
      .el-date-editor {
        width: 250px;
      }
    }
  }

  .chart-container {
    height: 300px;
    width: 100%;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .data-card .card-content {
    flex-direction: column;
    text-align: center;

    .card-icon {
      margin-right: 0;
      margin-bottom: 10px;
    }
  }

  .stats-row .stat-item {
    margin-bottom: 20px;
  }

  .chart-header {
    flex-direction: column !important;
    gap: 10px;

    .date-picker-wrapper .el-date-editor {
      width: 100% !important;
    }
  }

  .chart-container {
    height: 250px !important;
  }
}
</style>
